import React, { useState } from "react";
import moment from "moment";
import { accountType } from "@/types";
import { View, Text, Input, Button } from "@tarojs/components";
import { observer } from "mobx-react";
import Taro from "@tarojs/taro";
import http from "@/request";
import OperateList from "@/components/operateList";
import Page from "@/components/page";
import account from "@/store/account";
import { ShowToast, ToPage } from "@/utils";
import { AtModal, AtModalAction, AtModalContent, AtModalHeader } from "taro-ui";
import PageNav from "@/components/pageNav";
import viewMode from "@/store/viewMode";
import "./index.scss"

const Accounts: React.FC = observer(() => {

    const [visible, setVisible] = useState(false)
    const [accountName, setAccountName] = useState('')

    const deleteItem = (item) => {
        if (account.activeAccount?.id === item.id) {
            ShowToast('不允许删除当前账本')
            return
        }
        Taro.showModal({
            title: '是否删除所选账本？',
            content: '',
            success: (res: any) => {
                if (res.confirm) {
                    http.delete(`/account/delete/${item.id}`).then(() => {
                        ShowToast("删除成功")
                        account.doUpDateAccount()
                    }).catch(err => {
                        ShowToast(err.msg || '删除失败')
                    })
                }
            }
        })
    }

    const openAddModal = () => {
        viewMode.setBehind(true)
        setAccountName('')
        setVisibleVal(true)
    }

    const addAccount = () => {
        viewMode.setBehind(false)
        http.post('/account/addOrUpdate', {
            name: accountName
        }).then((res) => {
            ShowToast('新增成功，即将进入账本详情').then(() => {
                editItem(res.data)
                setVisibleVal(false)
                account.doUpDateAccount()
            })
        }).catch(err => {
            ShowToast(err.msg || '新增账本失败')
        })
    }

    const setVisibleVal = (val) => {
        viewMode.setBehind(val)
        setVisible(val)
    }

    const editItem = (item) => {
        ToPage(`/pages/accounts/accountDetail/index?accountid=${item.id}`)
    }


    const AccountItem: React.FC<{ item: accountType }> = (props) => {
        const accountInfo = props as unknown as accountType
        return (<View className="account-item flex-row flex-item">
            <View className="account-content flex1" onClick={() => editItem(accountInfo)}>
                <View className="list-item-row font-size28">
                    <Text className="account-name flex1">{accountInfo.name}</Text>
                    {account.activeAccount?.id === accountInfo.id ? <Text className="account-name flex1">（当前账本）</Text> : null}
                </View>
                <View className="flex-row flex-item list-item-row font-size24">
                    <Text>状态：</Text>
                    <Text>{accountInfo.status === 1 ? '已启用' : '已停用'}</Text>
                </View>
                <View className="flex-row flex-item list-item-row font-size24">
                    <View className="flex1">
                        <Text>固定收支：</Text>
                        <Text>{accountInfo.fixedIncomeNum ? `${accountInfo.fixedIncomeNum}项` : '无'}</Text>
                    </View>
                    <View className="flex2">
                        <Text>创建时间：</Text>
                        <Text>{moment(accountInfo.createTime).format('YYYY-MM-DD HH:mm:ss')}</Text>
                    </View>
                </View>
            </View>
            <View className="move-action flex-row flex-center">
                <View onClick={() => editItem(accountInfo)} className="flex1 flex-row flex-center active-btn">
                    <Text className="iconfont icon-base-edit2"></Text>
                    <Text>编辑</Text>
                </View>
                <View onClick={() => deleteItem(accountInfo)} className="flex1 flex-row flex-center active-btn">
                    <Text className="iconfont icon-base-del"></Text>
                    <Text>删除</Text>
                </View>
            </View>
        </View>)
    }

    return (
        <Page className="accounts-page page-background text-main-color flex-column flex-item">
            <PageNav showBack className="report-page-header need-filter">账本列表</PageNav>
            <View className="account-list card-background need-filter">
                <View className="day-header flex-row flex-item">
                    <View className="date flex1">左划编辑/删除</View>
                    <View className="add-btn flex-row flex-item" onClick={openAddModal}>
                        <Text className="font-size24">新增账本</Text>
                        <Text className="iconfont font-size32 icon-base-add"></Text>
                    </View>
                </View>
                <View className="bottom-line border-main-color"></View>
                <OperateList
                    listData={account.accountList || []}
                    childNode={AccountItem}>
                </OperateList>
            </View>
            <AtModal isOpened={visible} closeOnClickOverlay={false}>
                <AtModalHeader>
                    <View className="modal-title">新增账本</View>
                </AtModalHeader>
                <AtModalContent>
                    {
                        visible ?
                            <Input className="target-val-input"
                                placeholder-class="placeholder-style"
                                placeholder="请输入账本名称"
                                maxlength={10}
                                value={accountName}
                                onInput={e => setAccountName(e.detail.value)}>
                            </Input> : null
                    }
                </AtModalContent>
                <AtModalAction>
                    <Button onClick={() => setVisibleVal(false)}>取消</Button>
                    <Button onClick={addAccount}>确定</Button>
                </AtModalAction>
            </AtModal>
        </Page>
    )
})



export default Accounts